﻿using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Entities.Models;
using Microsoft.EntityFrameworkCore;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Atmk.WaterMeter.MIS.Logic.TempLogic
{
    public class NBCallbackDAL
    {
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 电信回调接口向结算表插入方法
        /// </summary>
        /// <param name="serviceData"></param>
        /// <param name="meterCodeIdMap"></param>
        /// <param name="eventTime"></param>
        //public async void InsertSettlementDay(WaterMeter.MIS.Entities.DeviceData serviceData, MeterCodeIdMap meterCodeIdMap, DateTime eventTime)
        //{
        //    await Task.Run(() =>
        //    {
        //        try
        //        {
        //            using (var context = new atmk_wmdb_devContext())
        //            {
        //                //取当天数据
        //                var settlementDay_Today = context.SettlementDay.FirstOrDefault(m => m.MeterNumber == meterCodeIdMap.Number && m.ReadTime.ToString("yyyy-MM-dd") == eventTime.ToString("yyyy-MM-dd"));
        //                //取上一次数据（正常是昨天）
        //                var settlementDay_Yesterday = context.SettlementDay.Where(m => m.MeterNumber == meterCodeIdMap.Number && Convert.ToDateTime(m.ReadTime.ToString("yyyy-MM-dd")) < Convert.ToDateTime(eventTime.ToString("yyyy-MM-dd"))).OrderByDescending(m => m.ReadTime).FirstOrDefault();

        //                var readString = Base64Convert.ConvertBytes(serviceData.current);
        //                var readValue = Convert.ToDecimal(BytesConvert.BitConvertInts(readString, 6).First() / 100.00);

        //                if (settlementDay_Today == null)
        //                {
        //                    var SettlementDayEntity = new SettlementDay()
        //                    {
        //                        MeterNumber = meterCodeIdMap.Number,
        //                        Value = readValue,                   //上报数值
        //                        ReadTime = eventTime,           //上报时间
        //                        SettlementState = 0,                //是否结算  0未结算 1已结算
        //                        Dosage = settlementDay_Yesterday == null ? 0 : readValue - settlementDay_Yesterday.Value, //用量
        //                        ProjectId = meterCodeIdMap.ProjectId,
        //                        DistrictId = meterCodeIdMap.DistrictId,
        //                        OwerId = meterCodeIdMap.OwerId,
        //                        MeterId = meterCodeIdMap.MeterId
        //                    };
        //                    context.SettlementDay.Add(SettlementDayEntity);
        //                    context.SaveChanges();
        //                }
        //                else
        //                {
        //                    settlementDay_Today.Value = readValue;
        //                    settlementDay_Today.Dosage = settlementDay_Yesterday == null ? readValue-settlementDay_Today.Value : readValue - settlementDay_Yesterday.Value;
        //                    settlementDay_Today.ReadTime = eventTime;
        //                    context.Update(settlementDay_Today);
        //                    context.SaveChanges();
        //                }

        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            _logger.Debug($"InsertSettlementDay方法 记录数据异常：{ex.Message}");
        //            _logger.Error($"InsertSettlementDay方法 记录数据异常：{ex.Message}");
        //        }
        //    });
        //}
        /// <summary>
        /// 原始上报数据记录
        /// </summary>
        /// <param name="meterNumber"></param>
        /// <param name="serviceData"></param>
        /// <param name="eventTime"></param>
        /// <returns></returns>
        //public int MeterRecordSave(WaterMeter.MIS.Entities.DeviceData serviceData, MeterCodeIdMap meterCodeIdMap, DateTime eventTime)
        //{
        //    try
        //    {
        //        using (var context = new atmk_wmdb_devContext())
        //        {
        //            //获取水表当前所有记录
        //            var meterReadingRecords_Today = context.MeterReadingRecord.Where(m => m.Number == meterCodeIdMap.Number&& m.ReadTime.ToString("yyyyMMdd") == eventTime.ToString("yyyyMMdd")).OrderByDescending(r => r.ReadTime).ToList();
        //            //判断是否重复数据
        //            if (!meterReadingRecords_Today.Any(m => m.ReadTime >= eventTime))
        //            {
        //                //当前水表读数
        //                var readString = Base64Convert.ConvertBytes(serviceData.current);
        //                var readInt = BytesConvert.BitConvertInts(readString, 6).First();
        //                //创建需要保存的水表数据
        //                var meterReadingRecord = new MeterReadingRecord()
        //                {
        //                    Number = meterCodeIdMap.Number,
        //                    ProjectId = meterCodeIdMap.ProjectId,
        //                    DistrictId=meterCodeIdMap.DistrictId,
        //                    OwerId=meterCodeIdMap.OwerId,
        //                    MeterId= meterCodeIdMap.MeterId,
        //                    ReadTime = eventTime,
        //                    Value = readInt / 100.00,
        //                    ValveState = serviceData.valve,
        //                    MsgType = serviceData.msgtype,
        //                    Warning = serviceData.warning,//表头 光电直读 异常报警
        //                                                  //Voltage = ((serviceData.voltage + 150) * 0.01).ToString(System.Globalization.CultureInfo.CurrentCulture),
        //                    Voltage = (serviceData.voltage + 150) * 0.01,
        //                    Value24Type = 1, //0未知1当前数据2冻结数据
        //                    CreateTime = DateTime.Now,
        //                    RecordState = 0
        //                };
        //                context.Add(meterReadingRecord);
        //                //context.SaveChanges();
        //                //历史水表读数
        //                var history = BytesConvert.BitConvertInts(Base64Convert.ConvertBytes(serviceData.history), 6);
        //                List<MeterReadingRecord> MRRs = new List<MeterReadingRecord>();
        //                //MRRs.Add(meterReadingRecord);
        //                int tt = 0;
        //                //如果 小时历史数据是正序  1，2，3，4 就打开下面注释
        //                //foreach (var item in history.Reverse())
        //                foreach (var item in history)
        //                {
        //                    //判断历史数据前100条中  是否存在该小时数据
        //                    if (!meterReadingRecords_Today.Where(m => m.Value24Type == 2 && m.ReadTime.ToString("yyyyMMdd HH") == eventTime.AddHours(-tt).ToString("yyyyMMdd HH")).Any())
        //                    {
        //                        meterReadingRecord = new MeterReadingRecord
        //                        {
        //                            Number = meterCodeIdMap.Number,
        //                            ProjectId = meterCodeIdMap.ProjectId,
        //                            DistrictId = meterCodeIdMap.DistrictId,
        //                            OwerId = meterCodeIdMap.OwerId,
        //                            MeterId =meterCodeIdMap.MeterId,
        //                            ReadTime = eventTime.AddHours(-tt),
        //                            Value = item / 100.00,
        //                            ValveState = serviceData.valve,
        //                            MsgType = serviceData.msgtype,
        //                            Warning = serviceData.warning,//表头 光电直读 异常报警
        //                                                          //Voltage = ((serviceData.voltage + 150) * 0.01).ToString(System.Globalization.CultureInfo.CurrentCulture),
        //                            Voltage = (serviceData.voltage + 150) * 0.01,
        //                            Value24Type = 2, //2历史数据  1当前数据
        //                            CreateTime = DateTime.Now,
        //                            RecordState = 0
        //                        };
        //                        //MRRs.Add(meterReadingRecord);
        //                        context.Add(meterReadingRecord);
        //                    }
        //                    tt++;
        //                }
        //                //context.AddRange(MRRs);
        //                return context.SaveChanges();
        //            }
        //            return 0;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.Error($"MeterRecordSave 记录数据异常：{ex.Message}");
        //        return 0;
        //    }
        //}

        ///// <summary>
        ///// 磁攻击报警记录数据
        ///// </summary>
        ///// <param name="serviceData"></param>
        ///// <param name="meterCodeIdMap"></param>
        ///// <param name="eventTime"></param>
        //public async void InsertWarningMagnetism(WaterMeter.MIS.Entities.DeviceData serviceData, MeterCodeIdMap meterCodeIdMap, DateTime eventTime)
        //{
        //    await Task.Run(() =>
        //    {
        //        try
        //        {
        //            using (var context = new atmk_wmdb_devContext())
        //            {
        //                var readString = Base64Convert.ConvertBytes(serviceData.current);
        //                var readValue = BytesConvert.BitConvertInts(readString, 6).First() / 100.00;

        //                var warningMagnetism = new WarningMagnetism()
        //                {
        //                    MeterNumber = meterCodeIdMap.Number,
        //                    Value = readValue,                   //上报数值
        //                    ReadTime = eventTime,           //上报时间
        //                    Voltage = ((serviceData.voltage + 150) * 0.01).ToString(System.Globalization.CultureInfo.CurrentCulture),
        //                    TapState = serviceData.valve,
        //                    MsgType = serviceData.msgtype,
        //                    ProjectId = meterCodeIdMap.ProjectId,
        //                    DistrictId = meterCodeIdMap.DistrictId,
        //                    OwerId = meterCodeIdMap.OwerId,
        //                    MeterId = meterCodeIdMap.MeterId,
        //                    CreateTime=DateTime.Now
        //                };
        //                context.WarningMagnetism.Add(warningMagnetism);
        //                context.SaveChanges();
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            _logger.Debug($"InsertWarningMagnetism 磁报警记录数据异常：{ex.Message}");
        //            _logger.Error($"InsertWarningMagnetism 磁报警记录数据异常：{ex.Message}");
        //        }
        //    });
        //}
    }
}
